package com.canyou.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Json字符串转换工具类
 *
 * @author cgz
 * @date 2019/06/16
 */
@Component
@Slf4j
public class JsonUtils {

    private static ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        JsonUtils.objectMapper = objectMapper;
    }

    /**
     * 对象转字符串
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String toString(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 字符串转对象
     *
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T toObject(String str, Class<T> clazz) {
        if (StringUtils.hasText(str) || clazz == null) {
            return null;
        }
        try {
            return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }


    /**
     * 判断参数中是否存在文件
     *
     * @param obj
     * @return
     */
    public static Object[] transFile(Object[] obj) {
        Object[] result = obj.clone();
        for (int i = 0; i < obj.length; i++) {
            if (obj[i] instanceof MultipartFile) {
                result[i] = ((MultipartFile) obj[i]).getOriginalFilename();
            } else if (obj[i] instanceof MultipartFile[]) {
                MultipartFile[] files = ((MultipartFile[]) obj[i]);
                String[] names = new String[files.length];
                for (int j = 0; j < files.length; j++) {
                    names[j] = files[j].getOriginalFilename();
                }
                result[i] = names;
            } else if (obj[i] instanceof HttpServletRequest) {
                HttpServletRequest request = (HttpServletRequest) obj[i];
                result[i] = request.getContentLengthLong();
            } else if (obj[i] instanceof HttpServletResponse) {
                HttpServletResponse response = (HttpServletResponse) obj[i];
                result[i] = response.getBufferSize();
            }
        }
        return result;
    }
}